import { createRouter, createWebHistory, type RouteRecordRaw, RouterView, type RouteLocationRaw } from 'vue-router'
import { constantRoutes, LAYOUT, INDEX_ROUTE_NAME } from './router'
import { isExternal } from '@/utils/validate'
import { MenuType } from '@/utils/enums/appEnums'
import { markRaw } from 'vue'
import useUserStores from '@/utils/stores/modules/user'

// 匹配views目录下的组件
const modules = import.meta.glob('@/views/**/*.vue');
// 要过滤的目录
const notViews: string[] = ['components', 'pages', 'account', 'error'];

// 过滤views目录下的组件
export function filteredModules() {
    return Object.fromEntries(
        Object.entries(modules)
            // 第一步：过滤不需要的目录
            .filter(([key]) => {
                return !notViews.some(dir => {
                    // 使用正则表达式精确匹配目录
                    const pattern = new RegExp(`\\/${dir}\\/`);
                    return pattern.test(key);
                });
            })
            // 第二步：转换路径格式
            .map(([key, value]) => [
                key
                    .replace(/^\/src\/views\//, '')  // 使用正则表达式确保匹配开头
                    .replace(/\.vue$/, '')           // 严格匹配.vue后缀
                    .replace(/\/index$/, ''),        // 移除末尾的/index
                value
            ])
    );
}
// console.log(filteredModules , modules)

// 过滤路由所需的数据
export function filterAsyncRoutes(routes: any[], firstRoute = true, parentPath = '') {
    return routes.map((router) => {
        const currentPath = firstRoute ? `/${router.path}` : `${parentPath}/${router.path}`.replace(/\/+/g, '/')
        const routerRecord = createRouterRecord(router, firstRoute, currentPath)
        if (router.children) {
            routerRecord.children = filterAsyncRoutes(router.children, false, currentPath)
        }
        return routerRecord
    })
}


// 创建路由
export function createRouterRecord(route: any, firstRoute = true, parentPath = '') {
    //@ts-ignore
    const routerRecord: RouteRecordRaw = {
        path: isExternal(route.path) ? route.path : firstRoute ? `/${route.path}` : route.path,
        // Just use the route path as the name to avoid duplication
        name: route.path.replace(/^\/+/, '').replace(/\/+/g, '-'),
        meta: {
            title: route.name,
            hidden: route.hidden || false,
            type: route.type || MenuType.MENU,
            icon: route.icon || ''
        }
    }

    if (route?.redirect) {
        routerRecord.redirect = function (to: RouteLocationRaw) {
            if (typeof route.redirect === 'function') {
                return route.redirect(to)
            }
            return route.redirect
        }
    }

    switch (route.type) {
        case MenuType.CATALOG:
            routerRecord.component = firstRoute ? LAYOUT : markRaw(RouterView)
            if (!route.children) {
                routerRecord.component = markRaw(RouterView)
            }
            break
        case MenuType.MENU:
            routerRecord.component = loadComponent(route.component)
            break
    }


    return routerRecord
}

// 动态加载组件
export function loadComponent(component: string) {
    try {
        // 规范化路径
        const componentPath = `/src/views/${component}.vue`

        // 直接从原始 modules 中查找组件
        if (modules[componentPath]) {
            return modules[componentPath]
        }

        // 尝试匹配 index.vue
        const indexPath = `/src/views/${component}/index.vue`
        if (modules[indexPath]) {
            return modules[indexPath]
        }

        throw Error(`找不到组件${component}，请确保组件路径正确`)
    } catch (error) {
        console.error(error)
        return markRaw(RouterView)
    }
}


// 查找第一个有效路由
export function findFirstValidRoute(routes: RouteRecordRaw[]): string | undefined {
    for (const route of routes) {
        if (route.meta?.type == MenuType.MENU && !route.meta?.hidden && !isExternal(route.path)) {
            return route.name as string
        }
        if (route.children) {
            const name = findFirstValidRoute(route.children)
            if (name) {
                return name
            }
        }
    }
}


// 重置路由
export function resetRouter() {
    router.removeRoute(INDEX_ROUTE_NAME)
    const { routes } = useUserStores()
    routes.forEach((route: any) => {
        const name = route.name
        if (name && router.hasRoute(name)) {
            router.removeRoute(name)
        }
    })
}

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: constantRoutes
})

export default router